﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using cde.SystemCommon;
using Cit.CDE.ApplicationBlocks.Data;
using Cit.CDE.Net.Module;
using Cit.CDE.Net.Module.Commons;
using Cit.CDE.Net.Service;
using Cit.CDE.Net.Service.DataAccess;
using Cit.CDE.Net.Service.ModuleFactory;
using ConfigAndElse;

namespace Module
{
    /// <summary>
    /// Copyright (C)   jinggubang
    /// FileName:        Util.cs
    /// Author :         Wangbc
    /// CDT:             2011-04-01           
    /// Version:         1.0.0.0                
    /// Depiction:       工具类
    /// </summary>
    public class Util
    {
        /// <summary>
        /// 得到候补值对应的名字
        /// </summary>
        /// <returns></returns>
        public static string getCandidate(CDEEntityManager em, string attributeName, string value)
        {
            string name = string.Empty;
            List<CDECandidate> list = LoadCandidates(em, attributeName);
            foreach (CDECandidate date in list)
            {
                if (date.Value.Equals(value))
                {
                    name = date.Label;
                    break;
                }
            }
            return name;
        }

        /// <summary>
        /// 得到候补值名字对应的VALUE
        /// </summary>
        /// <returns></returns>
        public static string getCandidateValue(CDEEntityManager em, string attributeName, string name)
        {

            string value = string.Empty;
            CDEAttribute CandidateAttribute = em.getAttribute(attributeName);
            if (CandidateAttribute != null)
            {
                if (CandidateAttribute.getP_Colmun() != null)
                {
                    value = CandidateAttribute.getP_Colmun().getCandidateValue(Util.objectToString(name));
                }
            }
            return value;
        }


        /// <summary>
        /// 得到关联表对应字段的值
        /// </summary>
        /// <returns></returns>
        public static string getPointAttribValue(iEntityManager em, string attributeName, string attributeValue, string pointAttributeName)
        {
            string name = string.Empty;
            CDESearchCriteria sc = em.CreateSearchCriteria();
            sc.addCondition(attributeName, attributeValue);
            List<CDEEntity> list = em.LoadEntity(sc);
            if (list.Count > 0)
            {
                CDEEntity entity = list[0];
                name = objectToString(entity.get(pointAttributeName));
            }
            return name;
        }


        /// <summary>
        /// 获取候补值
        /// </summary>
        public static List<CDECandidate> LoadCandidates(CDEEntityManager em, string attributeName)
        {
            List<CDECandidate> list = new List<CDECandidate>();

            CDEColumn col = CDEColumnFactory.getColumnById(em.getAttribute(attributeName).Colum_p);

            if (col != null)
            {
                list = col.getCandidates();
            }

            return list;
        }

        /// <summary>
        /// 对象转字符型，null变空串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string objectToString(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return obj.ToString().Trim();
        }
        /// <summary>
        /// 对象转字符型，null变0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string objectToNumbString(object obj)
        {
            return objectToString(obj) == "" ? "0" : objectToString(obj);
        }

        ///<summary>
        ///获取数据库连接
        ///</summary>
        public static SqlConnection getCon()
        {
  
           string sConnectionString = DataAccessManager.connStr;
           return new SqlConnection(sConnectionString);
          
        }

        ///<summary>
        ///SQL得到DATASET
        ///</summary>
        public static DataSet DataSetRunSql(string sql, SqlParameter[] parameters)
        {
            SqlConnection con = getCon();
            SqlCommand cmd = new SqlCommand(sql, con);

            if (parameters != null)
            {
                foreach (SqlParameter param in parameters)
                {
                    cmd.Parameters.Add(param);
                }
            }
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            con.Open();
            //执行操作
            adapter.Fill(ds);
            con.Close();
            return ds;
        }

        /// <summary>
        /// ListEntityToDataTable
        /// </summary>
        /// <param name="_ListEntity"></param>
        /// <returns></returns>
        public static DataTable ListEntityToDataTable(List<CDEEntity> _ListEntity)
        {
            StringBuilder strXml = new StringBuilder();
            strXml.AppendLine("<Entities>");

            foreach (CDEEntity entity in _ListEntity)
            {
                //特殊字符过滤
                strXml.AppendLine(Module2Xml.Entity2Node(entity));
            }
            strXml.AppendLine("</Entities>");

            DataSet ds = new DataSet();
            StringReader sr = new StringReader(strXml.ToString());
            XmlTextReader xr = new XmlTextReader(sr);
            ds.ReadXml(xr);

            if (ds.Tables["Entity"] != null)
            {

                DataTable dt = ds.Tables["Entity"];

                //特殊字符过滤 反原
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        dt.Rows[j][i] = Module2Xml.SysString2Null(Module2Xml.UnReplaceForText(dt.Rows[j][i].ToString()));
                    }
                }

                return dt;
            }
            else
            {
                return new DataTable("Entity");
            }
        }

        /// <summary>
        /// DataTable转化为listEntity(在原有DataTable中加入新字段及值)
        /// </summary>
        /// <param name="em">CDEEntityManager</param>
        /// <param name="dt">DataTable</param>
        /// <param name="AttributeNewValue"> List<string[]></param>
        /// <returns></returns>
        public static List<CDEEntity> DataTableTolistEntity(CDEEntityManager em, DataTable dt, List<string[]> AttributeNewValue)
        {
            List<CDEEntity> listEntity = new List<CDEEntity>();

            if (dt.Rows.Count >= 1)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    CDEEntity entity = CDEEMServiceFactory.getEMService(em).CreateEntity();

                    entity.Operation = CDEDataOperation.INSERT;

                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        for (int c = 0; c < em.ListAttributes.Count; c++)
                        {
                            //判断Excel表头名称在LIST中的属性名称中的位置
                            if ((string)dt.Columns[j].ColumnName.ToString() == em.ListAttributes[c].Label)
                            {
                                //判断此属性名称是否是候补值
                                if (em.ListAttributes[c].getP_Colmun().isHaveCandidate())
                                {
                                    //根据Excel表数据获取在list中的候补值
                                    entity.set(em.ListAttributes[c], em.ListAttributes[c].getP_Colmun().getCandidateValue((string)dt.Rows[i][j]));
                                }
                                else
                                {
                                    entity.set(em.ListAttributes[c], (string)dt.Rows[i][j]);
                                }

                                break;
                            }
                            if (AttributeNewValue != null)
                            {
                                foreach (string[] str in AttributeNewValue)
                                {
                                    if (em.ListAttributes[c].Label == str[0])
                                    {
                                        entity.set(em.ListAttributes[c], str[1]);
                                    }
                                }
                            }
                        }
                    }
                    listEntity.Add(entity);
                }
            }
            return listEntity;
        }

        /// <summary>
        /// DataTable转化为listEntity
        /// </summary>
        /// <param name="em">CDEEntityManager</param>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<CDEEntity> DataTableTolistEntity(CDEEntityManager em, DataTable dt)
        {
            List<string[]> lstr = null;

            return DataTableTolistEntity(em, dt, lstr);
        }

        /// <summary>
        /// DataSet 转成 XML
        /// </summary>
        /// <param name="xmlDS"></param>
        /// <returns></returns>
        public static string ConvertDataSetToXML(DataSet xmlDS)
        {
            System.IO.MemoryStream stream = null;
            System.Xml.XmlTextWriter writer = null;

            try
            {
                stream = new System.IO.MemoryStream();
                //从stream装载到XmlTextReader
                writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Unicode);

                //用WriteXml方法写入文件.
                xmlDS.WriteXml(writer, XmlWriteMode.WriteSchema);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                stream.Read(arr, 0, count);

                System.Text.UnicodeEncoding utf = new System.Text.UnicodeEncoding();
                return utf.GetString(arr).Trim();
            }
            catch (System.Exception ex)
            {
                SaveNote(ex.ToString());
                throw ex;
            }
            finally
            {
                if (writer != null) writer.Close();
            }
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string randomNumber(int length)
        {
            string resultNum = "";

            StringBuilder result = new StringBuilder();

            System.Threading.Thread.Sleep(5);

            Random random = new Random(Guid.NewGuid().GetHashCode());

            List<int> number = new List<int>(10);

            for (int i = 0; i < 10; i++)
            {
                number.Add(i);
            }

            for (int i = 0; i < length; i++)
            {
                int tempNum = random.Next(0, number.Count);

                result.Append(number[tempNum]);

                number.RemoveAt(tempNum);
            }
            resultNum = result.ToString().Trim();

            if (resultNum.Length != length)
            {

                resultNum = randomNumber(length);
            }

            return resultNum;
        }

        /// <summary>
        /// 用guid生成随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string randomGuidCode(int length)
        {
            StringBuilder result = new StringBuilder();
            char[] guid = Guid.NewGuid().ToString("N").ToCharArray();
            for (int i = 0; i < guid.Length; i++)
            {
                if (i == length)
                {
                    break;
                }
                result.Append(guid[i]);
            }
            return result.ToString().ToUpper();

        }

        /// <summary>
        /// 得到唯一U币号
        /// </summary>
        /// <returns></returns>
        public static string GetUIDRandomGuidCode(Dictionary<string, CDEEntity> allUid, int length)
        {
            string uid = randomGuidCode(length);
            while (true)
            {
                if (allUid.Count > 0)
                {
                    if (!allUid.ContainsKey(uid))
                    {
                        break;
                    }
                    else
                    {
                        uid = randomGuidCode(length);
                    }
                }
                else
                {
                    break;
                }
            }
            return uid;
        }
        /// <summary>
        /// 适用于返回单行单列的查询语句
        /// </summary>
        /// <param name="sql">要执行的语句</param>
        /// <param name="type">命令类型</param>
        /// <param name="paras">参数集合</param>
        /// <returns>返回的结果</returns>
        public static string ExcuteScaler(string sql, CommandType type, params SqlParameter[] paras)
        {
            SqlConnection cn = getCon();
            object obj = null;
            try
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand(sql, cn);
                cmd.CommandType = type;
                if (paras != null && paras.Length > 0)
                    //将参数集合添加到命令对象的参数集合中去
                    cmd.Parameters.AddRange(paras);
                obj = cmd.ExecuteScalar();
            }
            catch(Exception ex)
            {
                SaveNote(ex.ToString());
            }
            finally
            {
                cn.Close();
            }
            if (obj != null)
                return obj.ToString();
            return "";
        }
        /// <summary>
        /// 适用于增、删、改的方法
        /// </summary>
        /// <param name="sql">要执行的语句</param>
        /// <param name="type">命令类型</param>
        /// <param name="paras">参数集合</param>
        /// <returns>true:成功;false:失败</returns>
        public static bool ExcuteNonQuery(string sql, CommandType type, params SqlParameter[] paras)
        {
            SqlConnection cn = getCon();
            int rows = 0;
            try
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand(sql, cn);
                //设置命令类型
                cmd.CommandType = type;
                if (paras != null && paras.Length > 0)
                    //将参数集合添加到命令对象的参数集合中去
                    cmd.Parameters.AddRange(paras);

                rows = cmd.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                SaveNote(ex.ToString());
            }
            finally
            {
                cn.Close();
            }
            return rows > 0 ? true : false;
        }
        /// <summary>
        /// 事务执行sql
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExcSql(string sql) 
        {
            int rows = -1;

            SqlConnection conn = getCon();
            conn.Open();
            SqlTransaction tran = conn.BeginTransaction();
            try
            {
                SqlCommand comm = conn.CreateCommand();

                comm.Connection = conn;
                comm.Transaction = tran;
                comm.CommandType = CommandType.Text;
                comm.CommandText = sql;

                rows = comm.ExecuteNonQuery();

                tran.Commit();

            }
            catch (SqlException ex)
            {
                SaveNote(ex.ToString());
                tran.Rollback();
            }
            finally 
            {
                conn.Close();
            }
            return rows;
        }
        /// <summary>
        /// 事务执行sql
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExcSql(List<string> sqlList)
        {
            int rows = -1;

            SqlConnection conn = getCon();
            conn.Open();
            SqlTransaction tran = conn.BeginTransaction();
            try
            {
                SqlCommand comm = conn.CreateCommand();

                comm.Connection = conn;
                comm.Transaction = tran;
                comm.CommandType = CommandType.Text;
                foreach (string sql in sqlList)
                {
                    comm.CommandText = sql;

                    rows = comm.ExecuteNonQuery();

                    if (rows < 0) 
                    {
                        tran.Rollback();
                        break;
                    }
                }
                tran.Commit();

            }
            catch (SqlException ex)
            {
                rows = -1;
                SaveNote(ex.ToString());
                tran.Rollback();
            }
            finally
            {
                conn.Close();
            }
            return rows;
        }
        /// <summary>
        /// sql取得结果
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable loadSql(string sql)
        {
            DataSet ds = new DataSet();
            SQLHelper.FillDataset(getCon(), CommandType.Text, sql, ds, "table");

            return ds.Tables["table"];
        }
        /// <summary>
        /// 非负浮点数
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsInteger(string s)
        {

            string pattern = @"^\d*(\.?\d*)?$";                // @"^-\d+$"用这个正则表达式是有问题的
            return Regex.IsMatch(s.Replace(",",""), pattern);
        }
        /// <summary>
        /// 时间格式且验证时间
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsDateIegal(string s)
        {
            //判断YYYY-MM-DD这种格式的，基本上把闰年和2月等的情况都考虑进去了
            //string pattern=@"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$";
            //加了时间验证的  
            //string pattern=@"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (19|20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$";

            string pattern = @"\b\d{4}((?:0[13578]|1[02])(?:0[1-9]|[12]\d|3[01])|02(?:0[1-9]|[12]\d)|(?:0[469]|11)(?:0[1-9]|[12]\d|30))\b";
            return Regex.IsMatch(s, pattern);

        }
        /// <summary>
        /// 转化日期格式
        /// </summary>
        /// <param name="timeString"></param>
        /// <returns></returns>
        public static string IsDateFormat(string timeString)
        {
            string Datastr = null;
            DateTime time = new DateTime();
            try
            {
                time = DateTime.ParseExact(timeString, "yyyyMMdd", null);
                Datastr = time.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "/");
                return Datastr;
            }
            catch (Exception ex)
            {
                try
                {
                    time = DateTime.Parse(timeString);
                    Datastr = time.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "/");
                    return Datastr;
                }
                catch (Exception e)
                {
                    Datastr = null;
                    return Datastr;
                }
            }

        }
        /// <summary>
        /// 特殊浮点型数据转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ChangeDouble(string str)
        {
            string changeDouble = string.Empty;
            if (str.StartsWith("."))
            {
                changeDouble = "0" + str;
            }
            else if (str.Trim().ToString() == "") 
            {
                changeDouble = "0";
            }
            else if (str.StartsWith("0") && !str.StartsWith("0."))
            {
                changeDouble = ChangeDouble(str.Substring(1, str.Length - 1));
            }
            else 
            {
                changeDouble = str;
            }
            return changeDouble.Replace(",", "");
        }
        /// <summary>
        /// 非负整数
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsInt(string s)
        {
            string pattern = @"^\d+$";
            return Regex.IsMatch(s, pattern);
        }
        /// <summary>
        /// 身份证号验证
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsIdCard(string s)
        {
            string pattern = @"^\d{15}(\d{2}[A-Za-z0-9])?$";
            return Regex.IsMatch(s, pattern);
        }
        
        /// <summary>
        /// 由城市编码获得城市名称序列
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string getCityFullName(string code)
        {
            string name = getCityName(code);
            if (name == "")
            {
                return string.Empty;
            }
            return getCityName(code.Substring(0, 2) + "0000") + "/" + getCityName(code.Substring(0, 4) + "00") + "/" + name;
        }
        /// <summary>
        /// 由城市编码获得城市名称
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string getCityName(string code)
        {
            string name = "";
            name = ExcuteScaler("select city_name from citykey where ctcode = '" + code + "'", CommandType.Text, null);
            return name;
        }
        /// <summary>
        /// 判断是不是假期
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static Boolean isHoliday(DateTime dt) 
        {
            Boolean result = false;

            string sql = @"SELECT COUNT(*) FROM HOLIDAYS 
                            WHERE DBO.DATE_FORMAT(HOLIDAY,'YYYY-MM-DD') = '" + dt.ToShortDateString() + "'";

            DataTable table = loadSql(sql);

            if (Convert.ToInt32(objectToString(table.Rows[0].ItemArray[0])) > 0) 
            {
                result = true;
            }
            return result;
        }
        /// <summary>
        /// 日期加法（排除节假日）
        /// </summary>
        /// <param name="startDate">开始时间</param>
        /// <param name="days">工作日天数</param>
        /// <returns></returns>
        public static DateTime AddDayWithoutHoliday(DateTime startDate, int days)
        {
            while (isHoliday(startDate))//跳过节假日（保证开始时间不是节假日）：如果开始时间是节假日，找到节假日的结束时间作为起始时间
            {
                startDate = startDate.AddDays(1);
                DateTime dt = startDate.Date;
                startDate = dt;
            }
            for (int i = 0; i < days; i++)
            {
                startDate = startDate.AddDays(1);
                if (isHoliday(startDate))
                {
                    do
                    {
                        startDate = startDate.AddDays(1);
                    } while (isHoliday(startDate));
                }
            }
            return startDate;
        }

        /// <summary>
        /// 日期减法（排除节假日）
        /// </summary>
        /// <param name="startDate">开始时间</param>
        /// <param name="days">工作日天数</param>
        /// <returns></returns>
        public static DateTime SubtractDayWithoutHoliday(DateTime startDate, int days)
        {
            //while (isHoliday(startDate))//跳过节假日（保证开始时间不是节假日）：如果开始时间是节假日，找到节假日的结束时间作为起始时间
            //{
            //    startDate = startDate.AddDays(-1);
            //    DateTime dt = startDate.Date;
            //    startDate = dt;
            //}
            for (int i = 0; i < days; i++)
            {
                startDate = startDate.AddDays(-1);
                if (isHoliday(startDate))
                {
                    do
                    {
                        startDate = startDate.AddDays(-1);
                    } while (isHoliday(startDate));
                }
            }
            return startDate;
        }
        /// <summary>
        /// 过滤掉文件中的单引号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceErrStr(string str)
        {
            string newStr = str;
            newStr = str.Replace("'", "");
            return newStr;
        }
        ///// <summary>
        ///// 转义单引号（手动拼SQL用）
        ///// </summary>
        ///// <param name="str"></param>
        ///// <returns></returns>
        //public static string ReplaceErrStr(string str)
        //{
        //    string newStr = str;
        //    newStr = str.Replace("'", "''");
        //    return newStr;
        //}
        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="note"></param>
        public static void SaveNote(string note)
        {
            FileStream stream = new FileStream(GetLogDirectory("Common") + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite);
            StreamWriter writer = new StreamWriter(stream);
            writer.WriteLine("================================================================");
            writer.WriteLine(string.Format("Note:\t{0}", note));
            writer.WriteLine(string.Format("DateTime:\t{0}\r\n\r\n", DateTime.Now.ToShortTimeString()));
            stream.Flush();
            writer.Close();
            stream.Close();
            stream.Dispose();
            writer.Dispose();
        }

        /// <summary>
        /// 日志目录
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string GetLogDirectory(string category)
        {
            string baseDirectory = string.Empty;
            //if ((System.Web. HttpContext.Current != null) && (HttpContext.Current.Server != null))
            //{
            //    baseDirectory = HttpContext.Current.Server.MapPath("~");
            //}
            //else
            //{
                baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            //}
            if ((baseDirectory[baseDirectory.Length - 1] != '/') && (baseDirectory[baseDirectory.Length - 1] != '\\'))
            {
                baseDirectory = baseDirectory + @"\";
            }
            baseDirectory = string.Format(@"{0}Log\{1}\", baseDirectory, category);
            if (!Directory.Exists(baseDirectory))
            {
                Directory.CreateDirectory(baseDirectory);
            }
            return baseDirectory;
        }
        
        /// <summary>
        /// 验证18位身份证格式
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        public static bool CheckCidInfo18(string cid)
        {
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" };
            
            double iSum = 0;
            
            Regex rg = new Regex(@"^\d{17}(\d|X|x)$");
            
            Match mc = rg.Match(cid);
            
            if (!mc.Success)
            {
                return false;
            }
            
            cid = cid.ToLower();
            
            cid = cid.Replace("x", "a");
            
            if (aCity[int.Parse(cid.Substring(0, 2))] == null)
            {
                return false;//非法地区
            }
            try
            {
                DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2));
            }
            catch
            {
                return false;//非法生日
            }
            for (int i = 17; i >= 0; i--)
            {
                iSum += (System.Math.Pow(2, i) % 11) * int.Parse(cid[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber);
            }
            if (iSum % 11 != 1)
            {
                return false;//非法证号
            }
            return true;
        }
        /// <summary>
        /// 验证15位身份证格式
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        public static bool CheckCidInfo15(string cid)
        {
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" };
            Regex rg = new Regex(@"^\d{15}$");
            Match mc = rg.Match(cid);
            if (!mc.Success)
            {
                return false;
            }
            cid = cid.ToLower();
            cid = cid.Replace("x", "a");
            if (int.Parse(cid.Substring(0, 2)) > aCity.Length)
            {
                return false;//非法地区
            }
            if (aCity[int.Parse(cid.Substring(0, 2))] == null)
            {
                return false;//非法地区
            }
            try
            {
                DateTime.Parse(cid.Substring(6, 2) + "-" + cid.Substring(8, 2) + "-" + cid.Substring(10, 2));
            }
            catch
            {
                return false;//非法生日
            }
            return true;
        }
        /// <summary>
        /// 15位转18位身份证号
        /// </summary>
        /// <param name="perIDSrc"></param>
        /// <returns></returns>
        public static string per15To18(string perIDSrc)
        {
            int iS = 0;
            //加权因子常数
            int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            //校验码常数
            string LastCode = "10X98765432";
            //新身份证号
            string perIDNew;
            perIDNew = perIDSrc.Substring(0, 6);
            //填在第6位及第7位上填上‘1’，‘9’两个数字
            perIDNew += "19";
            perIDNew += perIDSrc.Substring(6, 9);
            //进行加权求和
            for (int i = 0; i < 17; i++)
            {
                iS += int.Parse(perIDNew.Substring(i, 1)) * iW[i];
            }
            //取模运算，得到模值
            int iY = iS % 11;
            //从LastCode中取得以模为索引号的值，加到身份证的最后一位，即为新身份证号。
            perIDNew += LastCode.Substring(iY, 1);
            return perIDNew;
        }
        /// <summary>
        /// 18位转15位身份证号
        /// </summary>
        /// <param name="perIDSrc"></param>
        /// <returns></returns>
        public static string per18To15(string perIDSrc)
        {
            //前6位
            string str1 = perIDSrc.Substring(0, 6);
            //后9位
            string str2 = perIDSrc.Substring(8, 9);
            //新字符串
            string perIDNew = str1 + str2;
            return perIDNew;
        }



        /// <summary>
        /// 根据文件类型取文件类型图
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static string getImageByFileType(string fileType)
        {
            string imgPath = "../../images/course/";
            Dictionary<string, string> fileImages = SystemConfig.FileImageList;
            if (fileImages.ContainsKey(fileType))
            {
                string img = fileImages[fileType];
                imgPath = imgPath + img;
            }
            else
            {
                imgPath = imgPath + "default.png";//默认图片
            }

            return imgPath;
        }

    }
}
